<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRolesForm">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolelist" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index1 == 0 ? 'bdtop' : '','vcebter']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag>
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限渲染 -->
              <el-col :span="19">
                <!-- for循环嵌套渲染二级权限 -->
               <el-row  :class="[index2==0?'':'bdtop','vcebter']" v-for="(item2, index2) in item1.children"
              :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" >
                      {{item2.authName}}
                   </el-tag>
                       <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                      <el-tag
                      type="warning" closable @close="removeRightById(scope.row,item3.id)"
             v-for="(item3, index3) in item2.children"
              :key="item3.id">
              {{item3.authName}}
              
              </el-tag>
                  </el-col>
                   
                </el-row>
            

                </el-col>
              </el-col>
            </el-row>

            <pre></pre>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit"
            @click="showEditDialogVisible(scope.row.id)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" icon="el-icon-delete"
            @click="removeUserById(scope.row.id)"
              >删除</el-button
            >
            <el-button size="mini" 
            @click="showSetRightDialog(scope.row)"
            type="warning" icon="el-icon-setting"
            
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisible"
  width="50%"
  @close="setRightDialogClosed"
   >
  <!-- 树形控件 -->
  <el-tree :data="rightlist" 
  :props="treeProps"
  show-checkbox 
  node-key="id"
  default-expand-all 
  ref="treeRef"

  :default-checked-keys="defKeys"
   ></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRight">确 定</el-button>
  </span>
</el-dialog>
<!-- 编辑对话框 -->
      <el-dialog
  title="编辑"
  :visible.sync="editDialogVisible"
  width="30%" >
  <el-form :model="editRolesForm"
     ref="editFormRef" label-width="100px">
    <el-form-item label="角色名称" >
      <el-input v-model="editRolesForm.roleName"  ></el-input>
    </el-form-item>
    <el-form-item label="角色描述" >
      <el-input v-model="editRolesForm.roleDesc"  ></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary"  @click="editFormInfo">确 定</el-button>
  </span>
</el-dialog>

<!-- 添加角色对话框 -->

      <el-dialog
  title="添加角色"
  :visible.sync="addDialogVisible"
  @close="addDislogClosed"
  width="30%">
      <el-form :model="addRolesForm"
      ref="addRolesForm" label-width="100px">
      <el-form-item label="角色名称" >
        <el-input v-model="addRolesForm.roleName"  ></el-input>
      </el-form-item>
      <el-form-item label="角色描述" >
        <el-input v-model="addRolesForm.roleDesc"  ></el-input>
      </el-form-item> 
      </el-form>
       <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="addRolesUser">确 定</el-button>
      </span>
</el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      //默认选中节点的ID值数组
      defKeys:[],
      // 角色列表属性
      rolelist: [],
      //权限控件属性
      rightlist:[],
      //显示隐藏对话框
      setRightDialogVisible:false,
      treeProps:{
        label:'authName',
        children:'children'
      },
      editDialogVisible:false,
      addDialogVisible:false,
      editForm:{},
      editRolesForm:{
     roleName:'',
     roleDesc:'',
    },
    addRolesForm:{
       roleName: '',
        roleDesc: ''
    },
    editFormRules:{},
    //当前即将分配权限的角色id
    roleId:''
      
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {

    // 展示所有权限数据
    async showSetRightDialog(role){
      this.roleId=role.id
      const {data:res}=await this.$http.get('rights/tree')
      if (res.meta.status!==200) {
       return this.$message.error('获取权限数据失败')
      }
      this.rightlist=res.data
      //展示列表前获取leafkeys
      this.getLeafKeys(role,this.defKeys)

      this.setRightDialogVisible=true
    },
    
    // 根据id删除对应的权限
   async removeRightById(role,rightId){
     const confirmResult= await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

        if (confirmResult!=='confirm') {
          return this.$message.info('取消了删除')
        }
      const{data:res}= await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status!==200) {
        return this.$message.error('删除失败')
      }
      // this.getRolesList(); 此方法在重新获取列表后会渲染页面出现刷新并合起来的样式
      role.children=res.data
    },
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolelist = res.data
      // console.log(this.rolelist)
    },
    getLeafKeys(node,arr){
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item=>
        this.getLeafKeys(item,arr)
      )
    },
    // 监听对话框关闭
    setRightDialogClosed(){
      // 重置defKeys数组
      this.defKeys=[]
    },
    // 根据id删除角色
    async removeUserById(id){
      const Result=await this.$confirm('此操作将永久删除该文件,是否继续?','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning',
        center:true
      }).catch(e=>e)
      if (Result!=='confirm') {
        return this.$message.info('已取消删除')
      }else{
        const {data:res}=await this.$http.delete('roles/'+id)
        if (res.meta.status!==200) {
          return this.$meesage.error('删除失败!')
        }
        this.$message.success('删除成功')
        this.getRolesList()
 }
    },
    // 显示添加用户
    showAddRolesForm(){
      this.addDialogVisible=true  
    },
    //添加角色
    addRolesUser(){
      this.$refs.addRolesForm.validate(async valid=>{
        if (!valid) {
          return
        }
        const {data:res}=await this.$http.post
        ('roles',this.addRolesForm)
        if (res.meta.status!==201) {
          return this.$meesage.error('添加角色失败')
        }
        this.$message.success('添加成功')
        this.getRolesList()
        this.addDialogVisible=false
      })
    },
    //关闭时清空添加用户的填充信息
    addDislogClosed(){
      this.$refs.addRolesForm.resetFields()
    },
   // 得到修改用户的信息
   async showEditDialogVisible(id){
      const{data:res}=await this.$http.get('roles/'+id)
      if (res.meta.status!==200) {
        return this.$meesage.error('查询角色失败')
      }
      this.editRolesForm=res.data
      // console.log(this.editRolesForm)
      this.editDialogVisible=true
    },
     editFormInfo(){
    this.$refs.editFormRef.validate(valid=>{
      if (!valid) {
        return
      }
      this.$http
      .put('roles/'+this.editRolesForm.roleId,{
        roleName:this.editRolesForm.roleName,
        roleDesc:this.editRolesForm.roleDesc,
      })
      .then(res=>{
        if (res.data.meta.status!==200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功!')
        this.getRolesList();
      })
      this.editDialogVisible=false
    })
  },
  //确定为角色分配权限
  async allotRight(){
    const keys=[
      ...this.$refs.treeRef.getCheckedKeys(),
      ...this.$refs.treeRef.getHalfCheckedKeys()
    ]
    const idStr=keys.join(',')
    const{data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{
      rids:idStr
    })
    if (res.meta.status!==200) {
      return this.$message.error('分配权限失败')
    }
    this.$message.success('分配成功!')
    this.getRolesList();
    this.setRightDialogVisible=false;
  },
  },
 
}
</script>
<style lang="less" scoped>
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.vcebter{
  display: flex;
  align-items: center;
}
</style>
